import { Component, OnInit } from '@angular/core';
import {NzMessageService} from "ng-zorro-antd";
import {ResourceEditComponent} from "./resource-edit/resource-edit.component";
import {ModalHelper} from "@shared/helper/modal.helper";
import {ResourceService} from "./resource.service";
import {ACLService} from "@core/acl/acl.service";

@Component({
  selector: 'app-resource',
  templateUrl: './resource.component.html',
  styleUrls: ['./resource.component.scss']
})
export class ResourceComponent implements OnInit {

    data = [];
    expandDataCache = {};

    collapse(array, data, $event) {
        if ($event === false) {
            if (data.children) {
                data.children.forEach(d => {
                    const target = array.find(a => a.id === d.id);
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    convertTreeToList(root) {
        const stack = [], array = [], hashMap = {};
        stack.push({ ...root, level: 0, expand: true });

        while (stack.length !== 0) {
            const node = stack.pop();
            this.visitNode(node, hashMap, array);
            if (node.children) {
                for (let i = node.children.length - 1; i >= 0; i--) {
                    stack.push({ ...node.children[ i ], level: node.level + 1, expand: true, parent: node });
                }
            }
        }
        return array;
    }

    visitNode(node, hashMap, array) {
        if (!hashMap[ node.id ]) {
            hashMap[ node.id ] = true;
            array.push(node);
        }
    }

    constructor(
                public acl: ACLService,
                private resourceService: ResourceService,
                private nzMessage: NzMessageService,
                private modalHelper: ModalHelper) {
    }

    edit(i) {
        this.modalHelper.static(ResourceEditComponent, { i }, '').subscribe(() => {
            this.load();
            // this.nzMessage.info('回调，重新发起列表刷新');
        });
    }

    del(id) {
        this.resourceService.del(id).subscribe(() => {
            this.load();
            this.nzMessage.success('删除成功');
        });
    }

    load() {
        this.resourceService.getTree().subscribe(data => {
            this.data = data;
            this.data.forEach(item => {
                this.expandDataCache[ item.id ] = this.convertTreeToList(item);
            });
        });
    }

    ngOnInit() {
        this.load();
    }
}
